package com.wt.struggle.goodbye.wxutil

import android.app.Activity
import android.util.Log
import com.tencent.connect.UserInfo
import com.tencent.connect.common.Constants
import com.tencent.tauth.IUiListener
import com.tencent.tauth.Tencent
import com.tencent.tauth.UiError
import org.json.JSONObject

class QQUtils(val activity: Activity) {


    val SCORE = "get_simple_userinfo"

    var back: OnReturnQQLoginData? = null
    lateinit var tencent: Tencent


    /**
     * qq三方登录
     */
    fun qqLogin(back: OnReturnQQLoginData) {

        this.back = back

        tencent = Tencent.createInstance(Contact.QQ_APP_ID, activity.applicationContext)

        if (!tencent.isSessionValid) {

            Log.i("result", "qq授权返回-----${tencent.isSessionValid}")

            tencent.login(activity, SCORE, object : IUiListener {

                override fun onComplete(p0: Any?) {

                    Log.i("result", "result-----$p0")

                    val jsonObject: JSONObject = p0 as JSONObject
                    jsonLogin(jsonObject)

                }

                override fun onCancel() {

                }

                override fun onError(p0: UiError?) {

                }
            })
        }
    }

    private fun jsonLogin(jsonObject: JSONObject) {
        Log.i("result", "qq登录返回------" + jsonObject.toString())

        val token = jsonObject.getString(Constants.PARAM_ACCESS_TOKEN)
        val expires = jsonObject.getString(Constants.PARAM_EXPIRES_IN)
        val openId = jsonObject.getString(Constants.PARAM_OPEN_ID)

        tencent.setAccessToken(token, expires)
        tencent.openId = openId

        val qqToken = tencent.qqToken

        val userInfo = UserInfo(activity.applicationContext, qqToken)
        userInfo.getUserInfo(object : IUiListener {
            override fun onComplete(p0: Any?) {
                if (back != null) {
                    back!!.onBack(p0.toString())
                }

            }

            override fun onCancel() {


            }

            override fun onError(p0: UiError?) {

            }

        })


    }


    /**
     * 获取QQ用户信息返回接口
     */
    interface OnReturnQQLoginData {
        fun onBack(result: String)
    }
}